package com.algo.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

public class HttpRequestHandler extends SimpleChannelInboundHandler<HttpObject> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

		ByteBuf buffer = null;

		if (msg instanceof HttpRequest) {
			HttpRequest request = (HttpRequest) msg;
			RequestProcessor processor = RequestProcessorFactory.get(request.uri());
			if (processor == null) {
				buffer = Unpooled.copiedBuffer("未找到合适的处理器".getBytes());
			} else {
				buffer = Unpooled.copiedBuffer(processor.execute().getBytes());
			}
		}
		
		HttpResponse response = new DefaultFullHttpResponse(new HttpVersion("HTTP/1.1", true),
				HttpResponseStatus.OK, buffer);

		response.headers().add("Content-Type", "text/plain; charset=UTF-8");
		response.headers().add("Content-Length", buffer.array().length);

		ctx.channel().writeAndFlush(response);
		ctx.channel().close();
	}

	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		System.out.println("Registered");
	}

	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
		System.out.println("Unregistered");
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("Active");
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("Inactive");
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.channel().close();
	}

}
